// Generates the file outspongexy.txt, used by sponge.pv to describe the scene (menger sponge)
// level 4 works, level 5 is far too big and makes Eclipse crash
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Random;


import utils.SpongeCube; 
public class spongeSphere {
	
	public static void main(String[] args) {
		Random generator=new Random();
		PrintStream output;
		try{
		output=new PrintStream("/tmp/outspongexy.txt");
		
		
		ArrayList<SpongeCube> keep=new ArrayList<SpongeCube>();
		ArrayList<SpongeCube> discard=new ArrayList<SpongeCube>(); 
		ArrayList<SpongeCube> finalCubes=new ArrayList<SpongeCube>(); 
		SpongeCube seed=new SpongeCube(0,0,0,1); 
		keep.add(seed); 
		int limit=5; 
		for(int i=0;i<limit;i++){ // cut each cube in keep
			ArrayList<SpongeCube> keep2=new ArrayList<SpongeCube>();
			int nbdiscarded=0; 
			for(SpongeCube e:keep){
				double mx=e.getX(); 
				double my=e.getY();
				double mz=e.getZ(); 
				double size=e.getSide()/3; 
				for(int x1=-1; x1<=1;x1++)
					for(int y1=-1;y1<=1;y1++)
						for(int z1=-1;z1<=1;z1++){
							boolean disc=false; 
							SpongeCube n=null; 
							if((x1==0)&&(y1==0)&&(z1==0)) disc=true; 
							if((x1==0)&&(y1!=0)&&(z1==0)) disc=true; 
							if((x1!=0)&&(y1==0)&&(z1==0)) disc=true; 
							if((x1==0)&&(y1==0)&&(z1!=0)) disc=true;
							if(i<(limit-1)){
								n=new SpongeCube(mx+x1*size,my+y1*size,mz+z1*size,size);
								if(!disc) keep2.add(n);				
							}
							else{
							/*if((Math.abs(mx+x1*size)>0.49)||
								(Math.abs(my+y1*size)>0.49)||
								(Math.abs(mz+z1*size)>0.49))
								*/
								if(mx>=mz)
							{
								n=new SpongeCube(mx+x1*size,my+y1*size,mz+z1*size,size);
								if(!disc) keep2.add(n);
								
							}else System.out.println(i+" discard "+(nbdiscarded++));
							}  
						}// for z1
			}// for Sponge
			keep=keep2; 
		}// for i
		// keep : not interesting
		// discard : list of cubes to discard
		System.out.println("#declare tokeep=union{");
		output.println("#declare tokeep=union{");
		int index=0; 
		for(SpongeCube e:keep){
			//if(index++%1000==0) System.out.println(index); 
			//System.out.println(e);
			output.println(e); 
		}
		output.println("}"); 
		System.out.println("}"); 
		System.out.println(keep.size()); 
		}// try
		catch(Exception e){System.out.println("plante "+e); }
	}

}
